<?php

class Category extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'Categories';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('CateNameRewrite, BrandId', 'required'),
			array('Status, BrandId', 'numerical', 'integerOnly'=>true),
			array('CategoryName, CateNameRewrite, Descriptions', 'length', 'max'=>100),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('CategoryId, CategoryName, CateNameRewrite, Status, BrandId', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'brand' => array(self::BELONGS_TO, 'Brand', 'BrandId'),
			'orderDetail' => array(self::HAS_MANY, 'OrderDetail', 'CategoryId'),
			'product' => array(self::HAS_MANY, 'Product', 'CategoryId'),
			'subCategory' => array(self::HAS_MANY, 'SubCategory', 'CategoryId'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'CategoryId' => 'Category',
			'CategoryName' => 'Category Name',
			'CateNameRewrite' => 'Cate Name Rewrite',
			'Descriptions' => 'Descriptions',
			'Status' => 'Status',
			'BrandId' => 'Brand Id',
			'CreateDate' => 'Create Date',
			'UpdateDate' => 'Update Date',
		);
	}

	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('CategoryId',$this->CategoryId);
		$criteria->compare('CategoryName',$this->CategoryName,true);
		$criteria->compare('CateNameRewrite',$this->CateNameRewrite,true);
		$criteria->compare('Status',$this->Status);
		$criteria->compare('BrandId',$this->BrandId);
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function getAll($active=null) {
		$criteria = new CDbCriteria;
		$criteria->select = 't.*';
		if($active!== null)
		$criteria->condition = 't.Status="'.$active.'"';
		$criteria->order = 't.CategoryId DESC';
		$result = self::model()->findAll($criteria);
		if ($result)
			return $result;
		return array();
	}  
		// public function findByBrandId($id){
		// 	$criteria = new CDbCriteria;
		// 	$criteria->addInConddition('t.BrandId' => $id);
		// 	$result = self::model()->findAll($criteria);
		// 	if($result)
		// 		return $result;
		// 	return array();
		// }
}
